<template>
    <div class="app-container">
        <a-card class="box-card" :cardOpen="aCardOpen[0]">
            <div slot="header">
                <span>计划基本信息</span>
            </div>
            <div slot="header-toolbtn">
                <BackButton title="返回演练管理" :back="{ title: '演练管理', url: '/drill/drillList' }" />
            </div>
            <el-form ref="elForm" size="small" label-width="100px" label-position="left">
                <el-row :gutter="15">
                    <el-col :span="24">
                        <el-form-item label="计划标题" prop="drillTitle">
                            {{ info.drillTitle }}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="15">
                    <el-col :span="6">
                        <el-form-item label="所属部门" prop="dept">
                            {{ info.drillDept }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="演练日期" prop="date">
                            {{ info.drillDate }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="演练地点" prop="location">
                            {{ info.location }}
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </a-card>
        <a-card class="box-card" :style="{ marginTop: '15px' }" :cardOpen="aCardOpen[1]">
            <div slot="header">
                <span>演练事件基本信息</span>
            </div>
            <div slot="header-toolbtn">
                <el-button type="primary" size="mini" style="float: right" @click="handleSaveEventInfo">保存事件基本信息</el-button>
            </div>
            <el-form ref="elForm" :model="formData" size="medium" label-width="100px">
                <el-row :gutter="15">
                    <el-col :span="6">
                        <el-form-item label="事件名称" prop="eventName">
                            <el-input v-model="formData.eventName" placeholder="请输入事件名称" :style="{ width: '100%' }"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="事件类型" prop="eventType">
                            <el-select v-model="formData.eventType" placeholder="请选择事件类型" :style="{ width: '100%' }">
                                <el-option v-for="dict in dict.type.usetypecode_dict" :key="dict.value" :label="dict.label" :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="事件等级" prop="event_level">
                            <el-select v-model="formData.eventLevel" placeholder="请选择事件等级" :style="{ width: '100%' }">
                                <el-option v-for="dict in dict.type.eventlevelcode_dict" :key="dict.value" :label="dict.label" :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="发生时间" prop="eventTime">
                            <el-date-picker type="datetime" v-model="formData.eventTime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" :style="{ width: '100%' }" placeholder="请选择发生时间"> </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="15">
                    <el-col :span="6">
                        <el-form-item label="发生地" prop="eventLocaltion">
                            <el-input v-model="formData.eventLocaltion" placeholder="请选择发生地" :style="{ width: '100%' }"> </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="位置坐标" prop="coordinate">
                            <el-input v-model="formData.coordinate" placeholder="请选择位置坐标" :style="{ width: '100%' }" @focus="handleCoordPick"> </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="15">
                    <el-col :span="24">
                        <el-form-item label="事件简述" prop="contentTitle">
                            <el-input v-model="formData.contentTitle" type="textarea" placeholder="请输入事件简述" :style="{ width: '100%' }"> </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="15">
                    <el-col :span="24">
                        <el-form-item label="影响范围" prop="impactArea">
                            <el-input v-model="formData.impactArea" type="textarea" placeholder="请输入影响范围" :style="{ width: '100%' }"> </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="15">
                    <el-col :span="24">
                        <el-form-item label="周围环境" prop="surroundings">
                            <el-input v-model="formData.surroundings" type="textarea" placeholder="请输入周围环境" :style="{ width: '100%' }"> </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="15">
                    <el-col :span="24">
                        <el-form-item label="事件原因" prop="eventCause">
                            <el-input v-model="formData.eventCause" type="textarea" placeholder="请输入事件原因" :style="{ width: '100%' }"> </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </a-card>
        <a-card class="box-card" :style="{ marginTop: '15px' }" :cardOpen="aCardOpen[2]">
            <div slot="header">
                <span>参演角色配置</span>
            </div>
            <el-form ref="elForm" size="medium" label-width="100px">
                <el-row :gutter="15">
                    <el-form-item label="总指挥" prop="event_name">
                        <span :style="{ marginRight: '15px' }" v-if="formData.plaUserName != null">{{ formData.plaUserName }}</span>
                        <el-button type="primary" size="mini" @click="handleChiefPick">选择总指挥</el-button>
                    </el-form-item>
                </el-row>
                <el-row :gutter="15">
                    <el-form-item label="角色分组" prop="event_name">
                        <el-button type="primary" size="mini" @click="handleRoleGroupAdd">添加分组</el-button>
                    </el-form-item>
                </el-row>
                <el-row class="role-groups">
                    <div class="role-group-side">
                        <el-tree :data="groups" ref="groupNodeList" node-key="groupId" default-expand-all check-on-click-node highlight-current @node-click="onGroupNodeClick">
                            <span class="flow-node" slot-scope="{ node, data }">
                                <span class="flow-label">{{ data.groupName }}</span>
                                <span class="flow-btns">
                                    <el-button type="text" size="mini" @click.stop="onGroupNodeEdit(data)"> 修改 </el-button>
                                    <el-button type="text" size="mini" @click.stop="onGroupNodeDelete(data)"> 删除 </el-button>
                                </span>
                            </span>
                        </el-tree>
                    </div>
                    <div class="role-list">
                        <el-row>
                            <el-button type="primary" size="mini" @click="handleAddRole">添加参演人员</el-button>
                        </el-row>
                        <el-table :data="currentGroup.drillPractsGroupDepts" size="mini" border :style="{ width: '100%', marginTop: '15px' }">
                            <el-table-column prop="deptName" label="所属部门"> </el-table-column>
                            <el-table-column prop="userName" label="姓名"> </el-table-column>
                            <el-table-column prop="address" label="操作" width="100">
                                <template slot-scope="scope">
                                    <el-button @click="handleRoleRemove(scope.row)" type="text" size="small">移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-row>
            </el-form>
        </a-card>
        <a-card class="box-card" :style="{ marginTop: '15px' }" :cardOpen="aCardOpen[3]">
            <div slot="header">
                <span>基础流程配置</span>
            </div>
            <el-form ref="elForm" :model="formData" size="medium" label-width="100px">
                <el-row :gutter="15">
                    <el-col :span="24">
                        <el-form-item label="预案模板" prop="event_name">
                            <span :style="{ marginRight: '15px' }" v-if="formData.planId != 0">{{ formData.plaPlanName }}</span>
                            <el-button type="primary" size="mini" @click="handlePickPlan">选择预案</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="15">
                    <el-col :span="6">
                        <el-form-item label="响应级别" prop="event_name">
                            <el-select v-model="formData.responseLevel" placeholder="请选择响应级别" :style="{ width: '100%' }" @change="onPlanResponseLevelChange">
                                <el-option :key="0" label="请先选择预案" :value="0" v-if="formData.plaPlanId == null" />
                                <template v-else>
                                    <el-option :key="0" label="请选择响应级别" :value="0" />
                                    <el-option v-for="item in responseLevelOption" :key="item.value" :label="item.label" :value="item.value" />
                                </template>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row class="role-groups">
                    <div class="role-group-side">
                        <el-tree :data="flowData" ref="flowNodeList" node-key="handleId" default-expand-all check-on-click-node highlight-current @node-click="onFlowNodeClick">
                            <span class="flow-node" slot-scope="{ node, data }">
                                <span class="flow-label">{{ data.handleName }}</span>
                            </span>
                        </el-tree>
                    </div>
                    <div class="role-list">
                        <DrillTaskTable ref="drillTaskTableRef" :tasks="currentHandle.drillPractsHandleLevel.drillPractsTasks" :checkContent="currentHandle.drillPractsHandleLevel.checkContent" @add="handleDrillTaskAdd" @edit="handleDrillTaskEdit" @del="handleDrillTaskDel" @contentEdit="onHandleCheckContentEdit" />
                    </div>
                </el-row>
            </el-form>
        </a-card>
        <staff-choose-dialog ref="staffChooseDialog" :muilt="false" @Unitpersonnel="onStaffChoose" />
        <drill-role-group-edit ref="drillRoleGroupEdit" @handleOk="onRoleGroupSave" />
        <plan-picker ref="planPicker" @handleOk="onPlanSelected" />
        <drill-task-edit ref="drillTaskEdit" @handleOk="onDrillTaskSave" :needMsg="false" />
        <drill-sudden-scene-edit ref="drillSuddenSceneEdit" @handleOk="onDrillSuddenSceneSave" />
        <MapLocation ref="mapLocationRef" @onPicked="handleCoordPicked" />
    </div>
</template>
<script>
import ACard from "@/views/components/a-card/card.vue";
import StaffChooseDialog from "@/views/components/staffChooseDialog/index.vue";
import DrillRoleGroupEdit from "./components/DrillRoleGroupEdit.vue";
import PlanPicker from "@/views/components/planPicker/index.vue";
import DrillTaskEdit from "./components/DrillTaskEdit.vue";
import DrillSuddenSceneEdit from "./components/DrillSuddenSceneEdit.vue";
import * as DrillApi from "@/api/drill/drill.js";
import * as PlanApi from "@/api/plan/plan.js";
import Uploader from "@/views/components/uploader/index.vue";
import { setDrillLeader, setDrillResponseLevel } from "@/api/drill/content";
import { drillTaskSet } from "@/api/drill/task";
import DrillTaskTable from "./modules/DrillContentTaskTable.vue";
import MapLocation from "@/views/components/mapTool/MapLocation.vue";
import BackButton from "@/views/components/backButton/index.vue";

export default {
    name: "DrillContentEdit",
    components: {
        ACard,
        StaffChooseDialog,
        DrillRoleGroupEdit,
        PlanPicker,
        DrillTaskEdit,
        DrillSuddenSceneEdit,
        Uploader,
        DrillTaskTable,
        MapLocation,
        BackButton,
    },
    dicts: ["usetypecode_dict", "eventlevelcode_dict", "drillcate_dict", "sys_dept_type_dict"],
    data() {
        return {
            info: {},
            formData: {
                planId: 0,
                contentId: 0,
                eventName: "",
                eventType: "",
                eventLevel: "",
                eventLocaltion: "",
                eventTime: "",
                contentTitle: "",
                impactArea: "",
                surroundings: "",
                eventCause: "",
                plaUser: 0,
                plaUserName: "",
                plaPlanId: 0,
                plaPlanName: "",
                responseLevel: 0,
                coordinate: "",
            },
            groups: [],
            currentGroup: {},
            currentHandle: {
                drillPractsHandleLevel: {},
            },
            responseLevelOption: [
                {
                    label: "Ⅰ级响应",
                    value: 1,
                },
                {
                    label: "Ⅱ级响应",
                    value: 2,
                },
                {
                    label: "Ⅲ级响应",
                    value: 3,
                },
                {
                    label: "Ⅳ级响应",
                    value: 4,
                },
            ],
            planResponseLevels: [],
            staffPickType: "",
            planId: 0,
            planTitle: "",
            flowData: [
                {
                    flowId: 1,
                    flowTitle: "组建领导小组",
                },
            ],
            activeScene: "",
            sceneTabs: [],
            currentScene: null,
            planId: 0,
            aCardOpen: [true, false, false, false, false],
        };
    },
    provide() {
        return {
            groups: () => this.groups,
        };
    },
    computed: {},
    watch: {},
    created() {},
    mounted() {
        this.formData.planId = this.$route.query.planId;
        this.getPlanContent();
    },
    methods: {
        getPlanContent() {
            DrillApi.getDrillPlanInfo(this.formData.planId).then(res => {
                console.log(res);
                let data = res.data;
                this.info = {
                    drillTitle: data.drillPractsPlan.planTitle,
                    drillDept: data.drillPractsPlan.deptName,
                    drillDate: data.drillPractsPlan.planDate,
                    location: data.drillPractsPlan.planLocation,
                };
                this.formData = {
                    planId: data.planId,
                    contentId: data.contentId,
                    eventName: data.eventName,
                    eventType: data.eventType,
                    eventLevel: data.eventLevel,
                    eventLocaltion: data.eventLocaltion,
                    eventTime: data.eventTime,
                    contentTitle: data.contentTitle,
                    impactArea: data.impactArea,
                    surroundings: data.surroundings,
                    eventCause: data.eventCause,
                    plaUser: data.plaUser,
                    plaUserName: data.plaUserName,
                    plaPlanId: data.plaPlanId,
                    plaPlanName: data.plaPlanName,
                    responseLevel: Number(data.responseLevel),
                    coordinate: data.coordinate || "",
                };
                this.groups = data.drillPractsGroups;
                this.flowData = data.drillPractsHandles;
                // 情景tabs
                let tabs = [];
                if (data.drillPractsScenes != null && data.drillPractsScenes.length > 0) {
                    data.drillPractsScenes.forEach((s, i) => {
                        tabs.push(Object.assign(s, { name: String(i + 1) }));
                    });
                    this.sceneTabs = tabs;
                } else {
                    this.sceneTabs = [];
                }
                this.$nextTick(() => {
                    if (data.drillPractsGroups.length > 0) {
                        let group = null;
                        if (this.currentGroup.groupId != undefined) {
                            group = data.drillPractsGroups.find(val => val.groupId == this.currentGroup.groupId);
                        }
                        if (group) {
                            this.currentGroup = group;
                        } else {
                            this.currentGroup = data.drillPractsGroups[0];
                        }
                        // 自动定位到第一个流程
                        this.$refs.groupNodeList.setCurrentKey(this.currentGroup.groupId);
                        let node = this.$refs.groupNodeList.getCurrentNode();
                        this.onGroupNodeClick(this.currentGroup, node);
                    }
                    if (data.drillPractsHandles.length > 0) {
                        let handle = null;
                        if (this.currentHandle.handleId != undefined) {
                            handle = data.drillPractsHandles.find(val => val.handleId == this.currentHandle.handleId);
                        }
                        if (handle) {
                            this.currentHandle = handle;
                        } else {
                            this.currentHandle = data.drillPractsHandles[0];
                        }
                        // 自动定位到第一个流程
                        this.$refs.flowNodeList.setCurrentKey(this.currentHandle.handleId);
                        let handleNode = this.$refs.flowNodeList.getCurrentNode();
                        this.onFlowNodeClick(this.currentHandle, handleNode);
                    }
                    if (this.sceneTabs.length > 0 && this.currentScene == null) {
                        this.activeScene = "1";
                        this.currentScene = this.sceneTabs[0];
                    } else {
                        this.currentScene = this.sceneTabs.find(val => val.sceneId == this.currentScene.sceneId);
                    }
                });
            });
        },
        onGroupNodeClick(val) {
            this.currentGroup = val;
        },
        onGroupNodeEdit(data) {
            this.$refs.drillRoleGroupEdit.edit(data);
        },
        onGroupNodeDelete(data) {
            if (data.drillPractsGroupDepts != null && data.drillPractsGroupDepts.length > 0) {
                // 分组下还有人，先移除人
                this.$modal.msgError("该分组下还有参演人员，请先移除");
                return false;
            } else {
                this.$modal.confirm("是否确认删除该分组").then(() => {
                    DrillApi.delDrillRoleGroup(data.groupId).then(res => {
                        this.getPlanContent();
                    });
                });
            }
        },
        handleRoleRemove(data) {
            this.$modal.confirm("是否确认移除该参演人员").then(() => {
                // 调用移除参演人员接口
                DrillApi.delDrillRole(data.groupDeptId).then(res => {
                    this.$modal.msgSuccess("参演人员移除成功");
                    let roleIndex = this.currentGroup.drillPractsGroupDepts.findIndex(val => val.groupDeptId == data.groupDeptId);
                    this.currentGroup.drillPractsGroupDepts.splice(roleIndex, 1);
                });
            });
        },
        onStaffChoose(deptId, userId, user, dept) {
            if (this.staffPickType == "chief") {
                // 调用设置总指挥接口
                this.formData.plaUser = userId;
                setDrillLeader(this.formData.planId, { userId: userId, userName: user.userName }).then(res => {
                    this.$modal.msgSuccess("总指挥人员设置成功");
                    this.getPlanContent();
                });
            }
            if (this.staffPickType == "role") {
                // 调用给分组添加人员接口
                DrillApi.drillRoleAdd({
                    groupId: this.currentGroup.groupId,
                    userId: userId,
                    userName: user.userName,
                    deptId: deptId,
                    deptName: dept.name,
                    flag: 0,
                }).then(res => {
                    this.$modal.msgSuccess("参演人员添加成功");
                    this.getPlanContent();
                });
            }
        },
        handleChiefPick() {
            this.staffPickType = "chief";
            this.$refs.staffChooseDialog.showDialog("选择总指挥");
        },
        handleRoleGroupAdd() {
            this.$refs.drillRoleGroupEdit.add(this.formData.contentId);
        },
        onRoleGroupSave() {
            this.getPlanContent();
        },
        handleAddRole() {
            this.staffPickType = "role";
            this.$refs.staffChooseDialog.showDialog("选择参演人员");
        },
        handlePickPlan() {
            this.$refs.planPicker.showDialog();
        },
        onPlanSelected(data) {
            this.formData.plaPlanId = data.id;
            this.formData.plaPlanName = data.planName;
            this.formData.responseLevel = 0;
        },
        onFlowNodeClick(val) {
            this.currentHandle = val;
        },
        handleDrillTaskAdd() {
            let levelId = this.currentHandle.drillPractsHandleLevel.levelId;
            this.$refs.drillTaskEdit.add(levelId);
        },
        onDrillTaskSave(data) {
            drillTaskSet(data).then(res => {
                this.$modal.msgSuccess("演练任务编辑成功");
                this.getPlanContent();
            });
        },
        handleDrillTaskEdit(data) {
            this.$refs.drillTaskEdit.edit(data);
        },
        handleDrillTaskDel(data) {
            this.$modal.confirm("演练任务删除将不可恢复，是否确认删除？").then(() => {
                // 调用移除参演人员接口
                DrillApi.delDrillTask(data.taskId).then(res => {
                    this.$modal.msgSuccess("演练任务移除成功");
                    // 从列表里移除
                    let taskIndex = this.currentHandle.drillPractsHandleLevel.hdTasks.findIndex(val => val.taskId == data.taskId);
                    this.currentHandle.drillPractsHandleLevel.hdTasks.splice(taskIndex, 1);
                });
            });
        },
        handleSuddenSceneAdd() {
            this.$refs.drillSuddenSceneEdit.add(this.formData.contentId);
        },
        handleSceneChange() {
            this.currentScene = this.sceneTabs[Number(this.activeScene) - 1];
        },
        onDrillSuddenSceneSave(data) {
            // 添加突发情景
            this.getPlanContent();
        },
        handleSceneEdit(data) {
            this.$refs.drillSuddenSceneEdit.edit(data);
        },
        handleSaveEventInfo() {
            // 保存事件信息
            DrillApi.editDrillEventInfo(this.formData).then(res => {
                this.$modal.msgSuccess("演练事件信息保存成功");
                this.getPlanContent();
            });
        },
        onChangeRoleFlag(data) {
            console.log(data);
            DrillApi.setDrillRoleFlag({
                groupDeptId: data.groupDeptId,
                flag: data.flag,
            });
        },
        onPlanResponseLevelChange() {
            if (this.formData.responseLevel == 0) {
                return false;
            }
            // 设置预案和响应级别
            setDrillResponseLevel({
                contentId: this.formData.contentId,
                plaPlanId: this.formData.plaPlanId,
                plaPlanName: this.formData.plaPlanName,
                responseLevel: this.formData.responseLevel,
            }).then(res => {
                this.getPlanContent();
            });
        },
        onUploaded(data) {
            console.log(data);
            // 提交附件数据修改接口
            DrillApi.drillSceneAttachAdd({
                sceneId: this.currentScene.sceneId,
                attachId: data.attachid,
            }).then(res => {
                this.$modal.msgSuccess("突发情景附件添加成功");
                this.getPlanContent();
            });
        },
        onHandleCheckContentEdit(content) {
            this.currentHandle.drillPractsHandleLevel.checkContent = content;
            DrillApi.setDrillHandleCheckContent({
                levelId: this.currentHandle.drillPractsHandleLevel.levelId,
                checkContent: this.currentHandle.drillPractsHandleLevel.checkContent,
            }).then(res => {
                this.$modal.msgSuccess("流程检查内容修改成功");
            });
        },
        handleSceneDel() {
            this.$modal.confirm("突发情景删除后将无法恢复数据，是否删除？").then(() => {
                // 调用移除参演人员接口
                DrillApi.delSuddenScene(this.currentScene.sceneId).then(res => {
                    this.$modal.msgSuccess("突发情景移除成功");
                    this.currentScene = {};
                    this.getPlanContent();
                });
            });
        },
        onSceneContentEdit() {
            DrillApi.editSuddenScene({
                sceneId: this.currentScene.sceneId,
                sceneContent: this.currentScene.sceneContent,
            }).then(res => {
                this.$modal.msgSuccess("突发情景说明修改成功");
            });
        },
        onSceneCheckContentEdit() {
            DrillApi.editSuddenScene({
                sceneId: this.currentScene.sceneId,
                checkContent: this.currentScene.checkContent,
            }).then(res => {
                this.$modal.msgSuccess("突发情景检查内容修改成功");
            });
        },
        handleSceneAttachDel(data) {
            // 根据attachId删除突发情景附件
            DrillApi.delDrillSceneAttachByAttachId(data.attachid, data.sceneId).then(res => {
                this.$modal.msgSuccess("突发情景附件移除成功");
                this.getPlanContent();
            });
        },
        handleSceneAttachDownload(row) {
            this.download(`com/ComAttach/download/${row.attachid}`, {}, `${row.attachname}.${row.attachtype}`);
        },
        handleCoordPick() {
            this.$refs.mapLocationRef.showDialog();
        },
        handleCoordPicked(coord) {
            this.formData.coordinate = coord.join(",");
        },
    },
};
</script>
<style lang="scss" scoped>
.role-groups {
    display: flex;

    .role-group-side {
        min-width: 200px;
    }

    .role-list {
        flex: 1;
        margin-left: 15px;
        box-sizing: content-box;
        overflow: hidden;
    }
}

::v-deep {
    .el-tree-node__content {
        display: flex;

        .flow-node {
            flex: 1;
            display: flex;

            .flow-label {
                flex: 1;
                line-height: 28px;
            }

            .flow-btns {
                margin-right: 10px;
            }
        }
    }

    .el-button.tab-edit-btn {
        color: #13ce66;
        margin-left: 10px;
        font-size: 12px;
    }
}
</style>
